package com.aqie.easy.dfs;

import com.aqie.easy.structure.TreeNode;

/**
 * 110， 判断是否是高度平衡的二叉树 todo
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1
 */
public class IsBalanced {
    /**
     * 1.Bottom-Top 提前阻断 2ms
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        return depth2(root) != -1;
    }

    private int depth2(TreeNode root) {
        if (root == null) return 0;
        int left = depth2(root.left);
        if(left == -1) return -1;
        int right = depth2(root.right);
        if(right == -1) return -1;
        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
    }


    /**
     * 2,Top-Bottom  4ms
     * @param root
     * @return
     */
    public boolean isBalanced2(TreeNode root) {
        if (root == null) return true;
        return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    private int depth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }



}
